(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.limit.limitTree.createController', createController);
	createController.$inject = [ '$scope', '$filter', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService', 'limitService' ];
	function createController($scope, $filter, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, limitService) {
		var ctrl = this, info = $scope.$stateParams.params, errorMessage = {};
//		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.limit = {};
		ctrl.init = function() {
			var params = {'limitNodeId' : $filter('encode')(info.limitNodeId), 'parentLimitId' : $filter('encode')(info.parentLimitId)};
			authService.create(params).then(function(response) {
				var initLimit = response.data || info;
				// init general
				limitService.initGeneral(initLimit, $scope, ctrl).then(function() {
					// change layout for dynaparm by limitNode
					ctrl.changeLayoutConfig(initLimit, "create").then(function() {
						// init limitRule
						limitService.initLimitRule($scope, ctrl);
						ctrl.limit = initLimit;
						ctrl.limit.limitRules = [];
					});
				});
				
			});
		};
		
		ctrl.createSave = function() {
			if (ctrl.limit.taskId) {
				return authService.createContinueSave(ctrl.limit).then(saveSuccessful, saveFailed);
			} else {
				return authService.createSave(ctrl.limit).then(saveSuccessful, saveFailed);
			}
		};

		ctrl.createSubmit = function() {
			if (ctrl.limit.taskId) {
				return authService.createContinueSubmit(ctrl.limit).then(submitSuccessful, submitFailed);
			} else {
				return authService.createSubmit(ctrl.limit).then(submitSuccessful, submitFailed);
			}
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.limit.limitTree');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.limit.list',
					'state' : 'cda.limit.limitTree',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);
